package plp.functional2.primitive;

import java.util.Iterator;
import java.util.List;

import plp.expressions2.expression.Expressao;
import plp.expressions2.expression.Id;
import plp.expressions2.expression.Valor;
import plp.expressions2.memory.AmbienteCompilacao;
import plp.expressions2.memory.AmbienteExecucao;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.functional2.concurrency.MailBox;

public class Send implements Primitiva{

	private Message message;
	private Id idProcess;

	public void setIdProcess(Id idProcess) {
		this.idProcess = idProcess;
	}
	
	public Send(Id idProcessSender,	Id idProcessReceiver, List<Expressao> pattern) {
		super();
		this.message = new Message(idProcessSender, idProcessReceiver, pattern);
	}
	
	public Send(Id idProcessReceiver, List<Expressao> pattern) {
		super();
		this.message = new Message(null, idProcessReceiver, pattern);
	}
	
	public Send(Message message) {
		super();
		this.message = message;
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public boolean checaTipo(AmbienteCompilacao ambiente)
			throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {

		Expressao exp = null;
		boolean idChecado = false;
		List<Expressao> ids = message.getPattern();
		
		for (int i = 0; i<ids.size(); i++) {
			exp = ids.get(i);
			idChecado = exp.checaTipo(ambiente);
			if (!idChecado){
				break;
			}
		}
		
		return idChecado;
	}

	public void executar(AmbienteExecucao ambiente) {
		
		List<Expressao> exps = message.getPattern();
		if(exps.size() > 1){
			Iterator iterator = exps.iterator();
			iterator.next();
			for (int i = 1; iterator.hasNext();i++) {
				Expressao expressao = (Expressao) iterator.next();				
				exps.set(i, expressao.avaliar(ambiente));
			}
		}
		
		MailBox mail = MailBox.getInstance();
		mail.addMessage(message);System.out.println("### Message Sent ###");		
		return;
	}

}
